package com.alignet.gn.hibernate.dao;

import java.sql.Blob;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.alignet.gn.hibernate.TgnCasoPrueba;
import com.alignet.gn.hibernate.TgnDocCasoPrueba;
import com.alignet.gn.hibernate.TgnPassword;
import com.alignet.gn.hibernate.TgnRole;
import com.alignet.gn.hibernate.TgnSolicitud;
import com.alignet.gn.hibernate.TgnSubproducto;
import com.alignet.gn.hibernate.TgnUser;

public class TgnRequestDAO extends HibernateDaoSupport {
    private static final Logger log = LoggerFactory.getLogger(TgnRequestDAO.class);

    protected void initDao() {
    }

    public void save(TgnSolicitud transientInstance) {
	log.debug("saving TgnUser instance");
	try {
	    getHibernateTemplate().save(transientInstance);
	    log.debug("save successful");
	} catch (RuntimeException re) {
	   re.printStackTrace();
	}
    }
    
    public void saveDocument(TgnDocCasoPrueba transientInstance) {
    	log.debug("saving TgnDocCasoPrueba instance");
    	try {
    	    getHibernateTemplate().save(transientInstance);
    	    log.debug("save successful");
    	} catch (RuntimeException re) {
    	   re.printStackTrace();
    	}
        }
    
  

    public void update(TgnSolicitud transientInstance) {
    	System.out.println("updating TgnSolicitud instance");
    	try {
    	    getHibernateTemplate().update(transientInstance);
    	    getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
    	    System.out.println("update successful");
    	} catch (RuntimeException re) {
    		re.printStackTrace();
    	}
    }
    
    

    public void delete(TgnUser persistentInstance) {
	log.debug("deleting TgnUser instance");
	try {
	    getHibernateTemplate().delete(persistentInstance);
	    log.debug("delete successful");
	} catch (RuntimeException re) {
	    log.error("delete failed", re);
	    throw re;
	}
    }

    public TgnSolicitud findById(java.lang.Integer id) {
	System.out.println("getting TgnUser instance with id: " + id);
	try {
		System.out.println(getHibernateTemplate());
		TgnSolicitud instance = (TgnSolicitud) getHibernateTemplate().get("com.alignet.gn.hibernate.TgnSolicitud", id);
	    return instance;
	} catch (RuntimeException re) {
	    re.printStackTrace();
		log.error("get failed", re);
	    throw re;
	    
	}
    }
    
    
    public TgnSubproducto findSubproductoById(java.lang.Integer id) {
    	log.info("getting TgnSubproducto instance with id: " + id);
    	try {
    		TgnSubproducto instance = (TgnSubproducto) getHibernateTemplate().get(
    		    "com.alignet.gn.hibernate.TgnSubproducto", id);
    		return instance;
    	} catch (RuntimeException re) {
    		re.printStackTrace();
    	    log.error("get failed", re);
    	    throw re;
    	}
    }

    public List<TgnUser> findByExample(TgnUser instance) {
	log.debug("finding TgnUser instance by example");
	try {
	    List<TgnUser> results = (List<TgnUser>) getHibernateTemplate()
		    .findByExample(instance);
	    log.debug("find by example successful, result size: "
		    + results.size());
	    return results;
	} catch (RuntimeException re) {
	    log.error("find by example failed", re);
	    throw re;
	}
    }

    public List findByProperty(String propertyName, Object value) {
	log.debug("finding TgnUser instance with property: " + propertyName
		+ ", value: " + value);
	try {
	    String queryString = "from TgnUser as model where model."
		    + propertyName + "= ?";
	    return getHibernateTemplate().find(queryString, value);
	} catch (RuntimeException re) {
	    log.error("find by property name failed", re);
	    throw re;
	}
    }

    public List findAll() {
	log.debug("finding all TgnUser instances");
	try {
	    String queryString = "from TgnUser";
	    return getHibernateTemplate().find(queryString);
	} catch (RuntimeException re) {
	    log.error("find all failed", re);
	    throw re;
	}
    }

    public TgnUser merge(TgnUser detachedInstance) {
	log.debug("merging TgnUser instance");
	try {
	    TgnUser result = (TgnUser) getHibernateTemplate().merge(
		    detachedInstance);
	    log.debug("merge successful");
	    return result;
	} catch (RuntimeException re) {
	    log.error("merge failed", re);
	    throw re;
	}
    }

    public void attachDirty(TgnUser instance) {
	log.debug("attaching dirty TgnUser instance");
	try {
	    getHibernateTemplate().saveOrUpdate(instance);
	    log.debug("attach successful");
	} catch (RuntimeException re) {
	    log.error("attach failed", re);
	    throw re;
	}
    }

    public void attachClean(TgnUser instance) {
	log.debug("attaching clean TgnUser instance");
	try {
	    getHibernateTemplate().lock(instance, LockMode.NONE);
	    log.debug("attach successful");
	} catch (RuntimeException re) {
	    log.error("attach failed", re);
	    throw re;
	}
    }

    public static TgnRequestDAO getFromApplicationContext(ApplicationContext ctx) {
	return (TgnRequestDAO) ctx.getBean("TgnUserDAO");
    }

    public TgnUser findUserByLogin(final String login) {
    	System.out.println("finding TgnUser instance with property: "+ login);
    	 TgnUser user = null;

    	try {

    	    String queryString = "from TgnUser as model where model.vcTypeentity = ? and model.vcLogin = ? ";
    	    Object[] params = new Object[]{"3", login};
    	    List<TgnUser> x = getHibernateTemplate().find(queryString, params);

    	    System.out.println("total rows : "+x.size());

    	    if(x.size()==1){
    			log.debug("element found, login : "+login);
    			user = (TgnUser)x.get(0);
    			log.debug("user id/name : ".concat(user.getInIduser()+"").concat(" / ".concat(user.getVcName())));
    	    }else {
    			log.warn(" element not found, login : "+login);
			}
    	} catch (RuntimeException re) {
    		System.out.println("find by TgnUser failed"+ re);
    	    re.printStackTrace();
    	}
    	return user;
        }

    public List findByQuery(String queryString) {
		log.debug("findByQuery #1");
		return getHibernateTemplate().find(queryString);
	} 	
	public List findByCriteria(DetachedCriteria criteria, int firstResult, int maxResults) {
		log.debug("findByQuery #2");
		return getHibernateTemplate().findByCriteria(criteria, firstResult, maxResults);
	}

	public List findByCriteriaX(DetachedCriteria criteria) {
		log.debug("findByQuery #2");
		return getHibernateTemplate().findByCriteria(criteria);
	}

	

	public List<TgnRole> findRole() {
		
		
		DetachedCriteria criteria = DetachedCriteria.forClass(TgnRole.class)
	     .add(Restrictions.eq("vcTypeentity","3"))
	     //.add(Restrictions.eq("inIdentity",idCommerce))
	     .add(Restrictions.eq("vcEditable","1"))
	     .addOrder(Order.desc("dtRegistry"));
		
		return getHibernateTemplate().findByCriteria(criteria);
	} 
	
	public void registraPassword(String clave, TgnUser userExist, Integer idLogin) {
		TgnPassword pass = new TgnPassword();
		pass.setVcPwd(clave);
		Date d= new Date();
		pass.setDtRegistry(new Timestamp(d.getTime()));
		pass.setTgnUser(userExist);
		pass.setInIduserreg(idLogin);
		getHibernateTemplate().save(pass);
	}
	
	public void eliminaData(TgnDocCasoPrueba datos) {
		getHibernateTemplate().delete(datos);
	}
	
	public TgnUser findUser(Integer idUser){
		return getHibernateTemplate().get(TgnUser.class, idUser);
	}

	
	public TgnCasoPrueba findCcasoPrueba(Integer idCp){
		return getHibernateTemplate().get(TgnCasoPrueba.class, idCp);
	}

	public List findPassword(Integer inIduser) {
		List list = (List) getHibernateTemplate().find("SELECT dtRegistry FROM TgnPassword where tgnUser.inIduser=" + inIduser + " order by dtRegistry desc fetch first 1 rows only");
		return list;
	}

	public List findHours(Timestamp fecha, Integer inIduser) {
		List list = (List) getHibernateTemplate().find("SELECT * FROM TgnDetallePlanificacion where fecha='" + fecha + "' and inIdplanificacion.idIduserAsign=" + inIduser);
		return list;
	}
	
	public boolean esUnico(String vcLogin) {
		DetachedCriteria criteria = DetachedCriteria.forClass(TgnUser.class)
	     .add(Restrictions.eq("vcLogin",vcLogin));
		if(getHibernateTemplate().findByCriteria(criteria).size()>0){
			return false;
		}else{
			return true;
		}
		
	}

	public List<TgnUser> findResources(String type) {
		DetachedCriteria criteria = DetachedCriteria.forClass(TgnUser.class)
			     .add(Restrictions.eq("vcType",type))
			     .add(Restrictions.ne("chState","3"))
			     .addOrder(Order.desc("dtRegistry"));
				
		return getHibernateTemplate().findByCriteria(criteria);
	}

	public List<TgnSubproducto> findSubproducto() {
		DetachedCriteria criteria = DetachedCriteria.forClass(TgnSubproducto.class)
	     .add(Restrictions.eq("vcState","1"))
	     .addOrder(Order.desc("dtRegistry"));
		return getHibernateTemplate().findByCriteria(criteria);
		
	}

	public TgnSubproducto findSubproductoId(Integer idSub){
		return getHibernateTemplate().get(TgnSubproducto.class, idSub);
	}
	
	public List<TgnSubproducto> findSubproducto(Integer id) {
		TgnSubproducto tsub=new TgnSubproducto();
		
		List list = (List) getHibernateTemplate().find("SELECT distinct idIdsubproducto FROM TgnRequerimiento tgnUser  where tgnUser.inIdsolicitud=" + id + "");
		Integer[] in=new Integer[list.size()];
		System.out.println("Tamanio " + list.size());
		for (int i = 0; i < list.size(); i++) {
			Integer x = (Integer)list.get(i);
			in[i]=x;
		}
		
		DetachedCriteria criteria = DetachedCriteria.forClass(TgnSubproducto.class)
	    .add(Restrictions.in("inIdSubProducto",in));
		
		return getHibernateTemplate().findByCriteria(criteria);
	}

	public void saveTestCase(TgnCasoPrueba casoprueba) {
		log.debug("saving TgnCasoPrueba saveTestCase");
		try {
		    getHibernateTemplate().save(casoprueba);
		    log.debug("save successful");
		} catch (RuntimeException re) {
		   re.printStackTrace();
		}
		
	}

}